var Webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require('path');
var nodeModulesPath = path.resolve(__dirname, 'node_modules');
var buildPath = path.resolve(__dirname, 'dist');
var mainPath = path.resolve(__dirname, 'src', 'main.js');
var env = process.env.NODE_ENV


var entry = env=='production'?
  [mainPath]:
  [

    // For hot style updates
    'webpack/hot/dev-server',

    // The script refreshing the browser on none hot updates
    'webpack-dev-server/client?http://localhost:3001',

    // Our application
    mainPath
  ]

var plugins = env=='production'?
    [
      new ExtractTextPlugin("./css/app.css")
    ]:
    [
      new Webpack.HotModuleReplacementPlugin(),
      new ExtractTextPlugin("./css/app.css")
    ]

var config = {

  // Makes sure errors in console map to the correct file
  // and line number
  devtool: 'eval',
  entry: entry,

  externals: {
    "react": "React",
    "react-dom": "ReactDOM",
    "jquery": "jQuery",
    "marked": "marked",
    "-": "lodash",
    // "DatePicker": "DatePicker"
  },

  output: {

    // We need to give Webpack a path. It does not actually need it,
    // because files are kept in memory in webpack-dev-server, but an
    // error will occur if nothing is specified. We use the buildPath
    // as that points to where the files will eventually be bundled
    // in production
    path: buildPath,
    filename: 'bundle.js',

    // Everything related to Webpack should go through a build path,
    // localhost:3000/build. That makes proxying easier to handle
    publicPath: '/assets/'
  },
  module: {

    loaders: [

    // I highly recommend using the babel-loader as it gives you
    // ES6/7 syntax and JSX transpiling out of the box
    {
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: /node_modules/
    },
    {
      test: /.jsx?$/,
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: {
        presets: ['es2015', 'react']
      }
    },
    // Let us also add the style-loader and css-loader, which you can
    // expand with less-loader etc.
    {
      test: /\.css$/,
      loader: 'style!css'
    },
    {
      test: /\.scss$/,
      loader: (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") ?
                ('style!css?sourceMap!sass?sourceMap') : ExtractTextPlugin.extract("style", "css!sass")
    }
    ]
  },

  // We have to manually add the Hot Replacement plugin when running
  // from Node
  plugins: plugins
};

module.exports = config;
